package com.ldc.wandroid.ui.activitys;

import android.os.Bundle;
import android.view.View;

import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;

import com.ldc.common.config.ArgParams;
import com.ldc.common.model.LoginInfoModel;
import com.ldc.common.mvvm.BaseMvvmActivity;
import com.ldc.common.utils.SPUtils;
import com.ldc.common.utils.StringUtils;
import com.ldc.common.utils.ViewModelUtils;
import com.ldc.wandroid.R;
import com.ldc.wandroid.contracts.MeContract;
import com.ldc.wandroid.databinding.ActivityFirstBinding;
import com.ldc.wandroid.viewmodel.FirstViewModel;

public class FirstActivity extends BaseMvvmActivity<ActivityFirstBinding, FirstViewModel> {
    private String userName;
    private String passWord;


    @Override
    protected void onDestroy() {
        super.onDestroy();
        viewModel.getLoginInfo().removeObserver(this::loginInfoData);
    }

    @Override
    protected ActivityFirstBinding initViewBinding() {
        return ActivityFirstBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void main(Bundle savedInstanceState) {
        userName = SPUtils.getInstance().getString(ArgParams.USER_NAME);
        passWord = SPUtils.getInstance().getString(ArgParams.USER_PASSWORD);
        viewModel.getLoginInfo().observeForever(this::loginInfoData);
        getHandler().postDelayed(() -> {
            if (StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(passWord)) {
                login();
            } else {
                showLoginPage();
            }
        }, 800);
    }

    @Override
    protected FirstViewModel initViewModel() {
        return ViewModelUtils.getViewModel(this, FirstViewModel.class);
    }

    private void showLoginPage() {
        NavHostFragment hostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container);
        if (null == hostFragment) {
            return;
        }
        NavController navController = hostFragment.getNavController();
        navController.setGraph(R.navigation.login_register_nav_graph);
        Bundle bundle = new Bundle();
        navController.navigate(R.id.loginFragment, bundle);
    }


    private void loginInfoData(LoginInfoModel model) {
        showLoading(false);
        if (null == model) {
            return;
        }
        MainActivity.start(this);
        finish();
    }

    private void showLoading(boolean show) {
        viewBinding.loading.viewPd.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    public void login() {
        showLoading(true);
        viewModel.login(userName, passWord);
    }
}
